package com.wl.shop.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wl.shop.entity.Attachment;
import com.wl.shop.model.RestResponse;
import com.wl.shop.utils.QiniuFileUtil;

@Controller
@RequestMapping("file")
public class FileController extends BaseController{
	/**
     * 普通单文件上传 
     * @param upfile
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadfile",method=RequestMethod.POST)
    @ResponseBody
    public RestResponse uploadFile(@RequestParam(value = "upfile", required = false) MultipartFile file) throws Exception{
        Map<String,String> map = new HashMap<String, String>();
        if (file != null){
            //循环获取file数组中得文件
        	String fileName = file.getOriginalFilename();
            try {
                String url = QiniuFileUtil.upload(file);
                Attachment attachment = new Attachment();
                attachment.preInsert();
    			attachment.setFileName(fileName);
    			attachment.setFileType(file.getContentType());
    			attachment.setFileSize((float)file.getSize()/1024);
    			attachment.setUrl(url);
    			attachmentService.insert(attachment);
                map.put("url",url);
                map.put("name",fileName);
            }catch (Exception e){
                e.printStackTrace();
                return RestResponse.failure(e.getMessage());
            }
        }else{
        	return RestResponse.failure("没有获得文件");
        }
        return RestResponse.success().setData(map);
    }
    
    /**
     * wangEditor 编辑器文件上传(这个编辑器非要返回一段字符串)
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("wang")
    @ResponseBody
    public String uploadWang(@RequestParam(value = "upfile", required = false) MultipartFile file) throws Exception{
    	String url  = null;
    	if (file != null){
    		String fileName = file.getOriginalFilename();
    		try {
    			url= QiniuFileUtil.upload(file);
    			Attachment attachment = new Attachment();
    			attachment.preInsert();
    			attachment.setFileName(fileName);
    			attachment.setFileType(file.getContentType());
    			attachment.setFileSize((float)file.getSize()/1024);
    			attachment.setUrl(url);
    			attachmentService.insert(attachment);
    		}catch (Exception e){
    			e.printStackTrace();
    		}
    	}
    	return url;
    }
}
